<template>
    <div class="table">
        <MaskItem :imgPercentage="imgPercentage"></MaskItem>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-tickets"></i> 批次管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-row justify="end">
            <el-col :span="24">
                <el-button style="float: right;margin: 10px 0" type="primary" size="medium" @click="addBatchShow()">新增批次</el-button>
            </el-col>
        </el-row>
        <div class="container">
            <!--<div class="handle-box">-->
            <!--<el-input v-model="select_word" placeholder="筛选关键词" class="handle-input mr10"></el-input>-->
            <!--<el-button type="primary" icon="search" @click="search">搜索</el-button>-->
            <!--</div>-->
            <el-table :data="tableData" ref="multipleTable" border v-loading="loadingFlag">
                <!--<el-table-column type="index" width="40"></el-table-column>-->
                <!-- sortable -->
                <el-table-column label="批次号" prop="batch_id" width="150"></el-table-column>
                <el-table-column label="类型" prop="batch_type"></el-table-column>
                <el-table-column prop="name" label="开课时间">
                    <template slot-scope="scope">
                        {{scope.row.start_time | formatTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="报名截止日期">
                    <template slot-scope="scope">
                        {{scope.row.end_time | formatTime}}
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="状态">
                    <template slot-scope="scope">
                        {{ !scope.row.batch_state ? '未开始' : scope.row.batch_state == 1 ? '进行中' : '已结束' }}
                    </template>
                </el-table-column>
                <el-table-column label="报名人数" prop="apply_sum"></el-table-column>
                <el-table-column label="最大人数">
                    <template slot-scope="scope">
                        <span>{{scope.row.max_sum}}</span>
                        <el-button icon="el-icon-edit" size="mini" circle @click="editMaxSum(scope.row,scope.$index)"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="金奖打卡数量" prop="gold_num"></el-table-column>
                <el-table-column label="金奖条件说明" prop="gold_desc"></el-table-column>
                <el-table-column label="银奖打卡数量" prop="silver_num"></el-table-column>
                <el-table-column label="银奖条件说明" prop="silver_desc"></el-table-column>
                <el-table-column label="操作" width="400">
                    <template slot-scope="scope">
                        <el-button size="small" type="success" @click="joinUserBatch(scope.row)">添加用户加入</el-button>
                        <el-button size="small" type="warning" @click="openStudentList(scope.row)">查看学员列表</el-button>
                        <el-button size="small" type="primary" @click="editBatchShow(scope.row,scope.$index)">编辑</el-button>
                        <el-button size="small" type="danger" @click="delCourseBatchShow(scope.row,scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next, jumper" :total="total" :page-size="10">
                </el-pagination>
            </div>
        </div>

        <!-- 删除批次管理 提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <div class="del-dialog-cnt">
                <el-input v-model="pass_word" placeholder="请输入管理员密码" type="password"></el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitdelCourseBatch()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改最大人数 -->
        <el-dialog title="修改最大人数" :visible.sync="uploadVisible" width="300px" center>
            <div class="del-dialog-cnt">
                <el-input-number v-model="num" @change="handleChange" :min="1" label="描述文字"></el-input-number>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="uploadVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEditMaxSum()">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="新增批次" :visible.sync="newBatchVisible">
            <div class="del-dialog-cnt" style="text-align: left">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
                    <el-form-item label="开课日期" required v-if="!editStatus">
                        <el-col :span="11">
                            <el-form-item prop="startTime">
                                <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.startTime" style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="报名截止日期" required v-if="!editStatus">
                        <el-col :span="11">
                            <el-form-item prop="endTime">
                                <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.endTime" style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="类型选择" prop="type_id" v-if="!editStatus">
                        <el-select v-model="ruleForm.type_id" placeholder="请选择类型选择" style="float: left;">
                            <el-option :label="option.type_name" :value="option.type_id" v-for="(option,oIndex) in courseBatchList" :key="oIndex"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="最大人数" prop="max_sum">
                        <el-input v-model.number="ruleForm.max_sum" style="width: 100px;float: left;"></el-input>
                    </el-form-item>
                    <el-form-item label="老师名称" prop="teacher_name">
                        <el-input v-model="ruleForm.teacher_name" style="width: 100px;float: left;" placeholder="老师名称"></el-input>
                    </el-form-item>
                    <el-form-item label="上传老师形象" prop="teacher_icon">
                        <div>
                            <div class="crop-demo-btn">上传老师形象
                                <input class="crop-input" type="file" ref="cropInput1" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 'teacher_icon')"/>
                            </div>
                            <img :src="ruleForm.teacher_icon" class="pic-img" >
                        </div>
                    </el-form-item>
                    <el-form-item label="上传批次图片" prop="batch_image">
                        <div>
                            <div class="crop-demo-btn">上传批次图片
                                <input class="crop-input" type="file" ref="cropInput3" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 'batch_image')"/>
                            </div>
                            <img :src="ruleForm.batch_image" class="pic-img" >
                        </div>
                    </el-form-item>
                    <el-form-item label="金奖获奖条件" prop="gold_num">
                        <div>
                            <span style="float: left;">累计打卡</span>
                            <el-input v-model.number="ruleForm.gold_num" style="width: 100px;float: left;"></el-input>
                            <span> 次</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="金奖获奖奖品说明" prop="gold_desc">
                        <div>
                            <el-input maxlength="500" type="textarea" v-model="ruleForm.gold_desc" style="width: 300px;float: left;"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="银奖获奖条件" prop="silver_num">
                        <div>
                            <span style="float: left;">累计打卡</span>
                            <el-input v-model.number="ruleForm.silver_num" style="width: 100px;float: left;"></el-input>
                            <span> 次</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="银奖获奖奖品说明" prop="silver_desc">
                        <div>
                            <el-input maxlength="500" type="textarea" v-model="ruleForm.silver_desc" style="width: 300px;float: left;"></el-input>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item label="优惠券类型选择(不可修改)" prop="cake_id">
                        <el-select v-model="ruleForm.cake_id" placeholder="请选择类型选择" :disabled="editStatus" style="float: left;">
                            <el-option :label="option.cakeName" :value="option.cakeId" v-for="(option,oIndex) in couponTypeList" :key="oIndex"></el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="悦器礼盒图片上传" prop="gift_img">
                        <div>
                            <div class="crop-demo-btn">上传礼盒图片
                                <input class="crop-input" type="file" ref="cropInput3" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 'gift_img')"/>
                            </div>
                            <img :src="ruleForm.gift_img" class="pic-img" >
                        </div>
                    </el-form-item>
                    <el-form-item label="优惠券图片" v-if="ruleForm.coupon_img">
                        <div>
                            <!-- <div class="crop-demo-btn">上传优惠券图片
                                <input class="crop-input" type="file" ref="cropInput3" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 'coupon_img')"/>
                            </div> -->
                            <img :src="ruleForm.coupon_img" class="pic-img" >
                        </div>
                    </el-form-item>
                    <el-form-item label="带班老师微信号" prop="teacher_data">
                        <div>
                            <div class="crop-demo-btn">上传老师二维码
                                <input class="crop-input" type="file" ref="cropInput2" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 'teacher_data')"/>
                            </div>
                            <img :src="ruleForm.teacher_data" class="pic-img" >
                        </div>
                    </el-form-item>
                </el-form>

            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="newBatchVisible = false;getData()">取 消</el-button>
                <el-button type="primary" @click="submitBatch()">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="小程序授权用户" :visible.sync="wxUserVisible">
            <div>
                <div style="margin-bottom: 15px">
                    <el-input placeholder="请输入微信名称，要准确" v-model="searchWxUserName" @keyup.enter="acquireAccreditWxUser();wxUserPage=1">
                        <template slot="append">
                            <el-button type="primary" @click="acquireAccreditWxUser();wxUserPage=1">搜索</el-button>
                        </template>
                    </el-input>
                </div>
                <div>
                    <el-table :data="wxUserData" v-if="wxUserData.length" ref="multipleTable" border v-loading="loadingFlag">
                         <el-table-column label="头像">
                            <template slot-scope="scope">
                               <img width="100" :src="scope.row.user_info.avatarUrl" size="smll" alt="">
                            </template>
                        </el-table-column>
                         <el-table-column label="微信名称">
                            <template slot-scope="scope">
                               {{scope.row.user_info.nickName}}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button size="small" type="primary" @click="confirmJoinUser(scope.row)">加入该批次</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination" v-if="wxUserTotal">
                        <el-pagination :current-page="wxUserPage" @current-change="handleWxUserCurrentChange" layout="prev, pager, next, jumper" :total="wxUserTotal" :page-size="10">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="wxUserVisible = false">取 消</el-button>
            </span>
        </el-dialog>
        <!-- 删除批次管理 提示框 -->
        <el-dialog title="提示" :visible.sync="confirmWxUserVisible" width="300px" center>
            <div class="del-dialog-cnt">是否确认“{{selectedWxUser['user_info'] ? selectedWxUser['user_info']['nickName'] : ''}}”加入该批次？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="confirmWxUserVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitUserJoinCourseBatch()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {baiduCloud} from '@/config/env'
import {dateRegExp} from '@/config/filter'
import {
    obtainCourseBatchList,
    editCourseBatchMaxSum,
    delCourseBatch,
    appendCourseBatch,
    obtainCourseBatchTypeList,
    editCourseBatch,
    obtainCouponType,
    obtainAccreditWxUser,
    checkStudentBatch,
    obtainWXPayParam,
    amendCourseIndent,
    preserveUserinfo
} from "@/config/api"
import Mask from '../../../common/mask.vue'
import { upLoadFileToOSS } from '@/config/utils'
export default {
    name: "CourseBatchManage",
    components: {
        MaskItem: Mask
    },
    data() {
        return {
            // 百度云
            akBos: baiduCloud.akBos,
            skBos: baiduCloud.skBos,
            endpointBos: baiduCloud.endpointBos,
            bucketImgBos: baiduCloud.bucketBos +'/course/image',
            urlImgBos: baiduCloud.urlBos+'/course/image/',
            // 图片上传进度
            imgPercentage: 0,
            // 列表数据
            tableData: [],
            // 页码
            cur_page: 1,
            // 删除批次对话框
            delVisible: false,
            // 修改人数对话框
            uploadVisible: false,
            // 新增批次 弹窗 显示
            newBatchVisible: true,
            // 修改批次最大人数
            num: 1,
            // 是否编辑状态 
            editStatus: false,
            // 表单
            ruleForm: {
                // 开始时间
                startTime: '',
                // 结束时间
                endTime: '',
                // 最大人数
                max_sum: '',
                // 老师二维码
                teacher_data: '',
                // 批次理性
                type_id: '',
                // 老师名称
                teacher_name: '',
                // 老师头像
                teacher_icon: '',
                // 批次图片
                batch_image: '',
                // 金奖数量
                gold_num: '',
                // 金奖说明
                gold_desc: '',
                // 银奖数量
                silver_num: '',
                // 银奖说明
                silver_desc: '',
                // 礼盒图片
                gift_img: '',
                // 优惠券图片
                coupon_img: '',
                // 加载
                loadingFlag: false,
                // 优惠券类型ID
                cake_id: ''
            },
            rules: {
                type_id: [
                    {
                        required: true,
                        message: "请选择课程类型",
                        trigger: "change"
                    }
                ],
                startTime: [
                    {
                        type: "date",
                        required: true,
                        message: "请选择日期",
                        trigger: "change"
                    }
                ],
                endTime: [
                    {
                        type: "date",
                        required: true,
                        message: "请选择时间",
                        trigger: "change"
                    }
                ],
                max_sum: [
                    {
                        required: true,
                        message: "请输入最大人数"
                    },
                    {
                        type: 'number',
                        message: "请允许输入数字"
                    }
                ],
                gold_num: [
                    {
                        required: true,
                        message: "请输入金奖累计次数"
                    },
                    {
                        type: 'number',
                        message: "请允许输入数字"
                    }
                ],
                gold_desc: [
                    {
                        required: true,
                        message: "请输入金奖规则说明"
                    }
                ],
                silver_num: [
                    {
                        required: true,
                        message: "请输入银奖累计次数"
                    },
                    {
                        type: 'number',
                        message: "请允许输入数字"
                    }
                ],
                silver_desc: [
                    {
                        required: true,
                        message: "请输入银奖规则说明"
                    }
                ],
                teacher_name:[
                    {
                        required: true,
                        message: "输入老师名称",
                        trigger: "change"
                    }
                ],
                gift_img: [
                    {
                        required: true,
                        message: "请上传礼盒图片"
                    }
                ],
                coupon_img: [
                    {
                        required: true,
                        message: "请上传优惠券图片"
                    }
                ],
                teacher_data: [
                    {
                        required: true,
                        message: "请上传老师的微信二维码"
                    }
                ],
                batch_image: [
                    {
                        required: true,
                        message: "请上传批次图片"
                    }
                ],
                teacher_icon: [
                    {
                        required: true,
                        message: "请上传批次图片"
                    }
                ],
                cake_id: [
                    {
                        required: true,
                        message: "请选择优惠券类型",
                        trigger: "change"
                    }
                ]
                
                
            },
            // 保存点击的数据
            saveData: {},
            // 总条数
            total: 0,
            // 删除批次的时候，需要输入密码
            pass_word: "",
            // 课程类型列表
            courseBatchList: [],
            // 优惠券类型ID
            couponTypeList: [],
            // 微信授权用户 弹窗 显示
            wxUserVisible: false,
            // 是否确认该用户加入该批次 弹窗 显示
            confirmWxUserVisible: false,
            // 微信授权用户信息
            wxUserData: [],
            // 微信授权用户信息 页码
            wxUserPage: 1,
            // 搜索用户名称
            searchWxUserName: '',
            // 选择了 某微信用户
            selectedWxUser: {},
            // 选择了 某个批次
            selectedBatch: {},
            // 搜索出来的用户 总数量
            wxUserTotal: 0
        };
    },
    filters: {
        formatTime (time) {
            return dateRegExp(( time - 0 ),'yyyy-MM-dd')
        }
    },
    created() {
        // 获取列表数据
        this.getData();
        // 初始化百度云上传
        this.initBaiDuBce();
         // 获取课程类型
        this.obtainCourseBatchType();
        // 获取优惠券类型
        this.acquireCouponType();
    },
    mounted() {
        this.$nextTick(()=>{this.newBatchVisible= false;})
    },
    computed: {

    },
    methods: {
        // 获取 批次
        async getData() {
            this.loadingFlag = true;
            let data = await obtainCourseBatchList(this.cur_page);
            console.log("数据", data);
            this.tableData = data.list;
            this.total = data.total;
            this.loadingFlag = false;
        },
        // 获取优惠券类型
        async acquireCouponType () {
            const data = await obtainCouponType();
            if (data.status === 200) {
                this.couponTypeList = data.data;
            }
        },
        // 获取课程类型
        async obtainCourseBatchType () {
            let data = await obtainCourseBatchTypeList();
            console.log('获取课程类型:',data)
            this.courseBatchList = data.list;
        },
        // 编辑人数
        async editMaxSum(row, index) {
            this.uploadVisible = true;
            // 最大人数
            this.num = row.max_sum;
            // 保存被点击的数据
            this.saveData = row;
            console.log("编辑最大人数：", row, index);
        },
        // 确定修改批次最大人数
        async submitEditMaxSum() {
            // 隐藏对话框
            this.uploadVisible = false;
            await editCourseBatchMaxSum(this.saveData.batch_id, this.num)
                .then(res => {
                    console.log("确定修改批次最大人数", res);
                    if (res.msg === "success") {
                        this.$message({
                            message: "修改成功",
                            type: "success"
                        });
                        // 重新获取数据
                        this.getData();
                    } else {
                        this.$message.error("失败");
                    }
                })
                .catch(err => {
                    console.log("错误信息：", err);
                });
        },
        // 删除批次管理 对话框 显示
        delCourseBatchShow(row, index) {
            this.delVisible = true;
            // 保存被点击的数据
            this.saveData = row;
            console.log("删除批次管理 对话框 显示", row, index);
        },
        // 删除批次管理
        async submitdelCourseBatch() {
            // 对话框删除
            this.delVisible = false;
            await delCourseBatch(this.saveData.batch_id, this.pass_word,localStorage.getItem('ms_username'))
                .then(res => {
                    console.log("删除批次", res);
                    if (res.msg === "success") {
                        this.$message({
                            message: "删除成功",
                            type: "success"
                        });
                        // 重新获取数据
                        this.getData();
                    } else {
                        this.$message.error(res.msg);
                    }

                    this.pass_word = "";
                })
                .catch(err => {
                    console.log("错误信息：", err);
                });
        },
        // 新增批次 显示
        addBatchShow () {
            if (!this.courseBatchList.length) {
                this.$message.error('暂无课程类型选择，请先到课程类型页添加！');
                return false;
            };
            // 显示
            this.newBatchVisible = true;
            // 非编辑状态
            this.editStatus = false;
             // 数据初始化
            // this.ruleForm = {
            //     // 开始时间
            //     startTime: '',
            //     // 结束时间
            //     endTime: '',
            //     // 最大人数
            //     max_sum: '',
            //     // 老师二维码
            //     teacher_data: ''
            // };
            this.resetForm('ruleForm')
        },
        // 新增批次 提交
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    console.log(this.ruleForm,'提交的数据')
                    for (let i = 0; i < this.courseBatchList.length;i++) {
                        if (this.courseBatchList[i].type_id == this.ruleForm.type_id) {
                            this.ruleForm.batch_type = this.courseBatchList[i]
                        }
                    }
                    this.$set(this.ruleForm,'start_time',this.ruleForm.startTime.getTime())
                    this.$set(this.ruleForm,'end_time',this.ruleForm.endTime.getTime())
                    if (this.ruleForm.start_time > this.ruleForm.end_time) {
                        this.$message.error('报名时间不能超过报名截止时间！');   
                        this.$refs.ruleForm.validateField('endTime'); 
                        return false;
                    }
                    // 提交
                    appendCourseBatch(this.ruleForm)
                        .then(res => {
                            console.log('新增批次',res)
                            if (res.msg === 'success') {
                                this.$message({
                                    message: "新增成功",
                                    type: "success"
                                }); 
                            } else {
                                this.$message.error(res.msg);   
                            }
                            // 表单 隐藏
                            this.newBatchVisible = false;
                            // 重新获取数据
                            this.getData();
                        }).catch(err => {
                            console.error('报错信息',err)
                        })
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        // 编辑批次 提交
        async submitEditCourseBatch () {
            await editCourseBatch(this.ruleForm)
                .then(res => {
                    if (res.status === 200) {
                        this.$message({
                            message: "编辑成功",
                            type: "success"
                        }); 
                        // 表单 隐藏
                        this.newBatchVisible = false;
                        // 重新获取数据
                        this.getData();
                    } else {
                        this.$message.error('编辑失败');   
                    }
                })
                .catch(err => {
                    this.$message.error('编辑失败');   
                })
        },
        // 修改最大人数
        handleChange() {},
        // 编辑批次
        editBatchShow (item) {
            // 显示
            this.newBatchVisible = true;
            // 编辑状态
            this.editStatus = true;
            this.ruleForm = Object.assign({},item);
        },
        // 分页导航
        handleCurrentChange(val) {
            this.cur_page = val;
            this.getData();
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        // 初始化百度云上传
        initBaiDuBce(){
            let self = this;
            let bosConfig = {
                credentials: {
                    ak: self.akBos,
                    sk: self.skBos
                },
                endpoint: self.endpointBos  // 根据您选用bos服务的区域配置相应的endpoint
            };
            // let bucket = self.bucketBos; // 设置您想要操作的bucket
            self.client = new baidubce.sdk.BosClient(bosConfig);
        },
        // 准备上传
        async uploadTypeImg(event, key){
            let self = this;
            // 浏览器兼容 (FF不兼容event.srcElement)
            let evt = event.srcElement ? event.srcElement : event.target;
            let file = evt.files[0]; // 获取要上传的文件
            // 用户取消上传
            if(file == undefined){
                return;
            }
            // 开始上传
            let resUrl = await self.uploadModule(event);
            if (resUrl) {
                // 赋值
                self.ruleForm[key] = resUrl;
                // 清空上传控件
                evt.value = '';
            }
        },
        // 提交批次数据
        submitBatch () {
            if (this.editStatus) {
                // 提交编辑批次
                this.submitEditCourseBatch();
            } else {
                // 新增批次
                this.submitForm('ruleForm');
            }
        },
        // 上传模块
        uploadModule (event) {
            let self = this;
            return new Promise( async resolve => {
                // 浏览器兼容 (FF不兼容event.srcElement)
                let evt = event.srcElement ? event.srcElement : event.target;
                let file = evt.files[0]; // 获取要上传的文件
                // 用户取消上传
                if(file == undefined){
                    return;
                }
                const url = await upLoadFileToOSS(file, 'course/image');
                if (url) {
                    resolve(url)
                } else {
                     resolve(false)
                }
                // return false;
                // // 生成6位随机数
                // let chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
                // let res = "";
                // for(let i = 0; i < 6 ; i ++) {
                //     let id = Math.ceil(Math.random()*61);
                //     res += chars[id];
                // }
                // let key = res +'_'+new Date().getTime()+ '.' +file.name.split(/\./g).pop(); // 保存到bos时的key，您可更改，默认以文件名作为key
                // let blob = file;
                // let ext = key.split(/\./g).pop();
                // let mimeType = baidubce.sdk.MimeType.guess(ext);
                // if (/^text\//.test(mimeType)) {
                //     mimeType += '; charset=UTF-8';
                // }
                // let options = {
                //     'Content-Type': mimeType
                // };
                // self.client.putObjectFromBlob(self.bucketImgBos, key, blob, options)
                //     .then( res => {
                //         // 上传完成，添加您的代码
                //         console.log(key,res,'上传成功');
                //         // if (status === 1) {
                //         //     self.ruleForm.teacher_icon = self.urlImgBos + key;
                //         // } else if (status === 2)  {
                //         //     self.ruleForm.teacher_data = self.urlImgBos + key;
                //         // } else if (status === 3) {
                //         //     self.ruleForm.batch_image = self.urlImgBos + key;
                //         // }
                //         // self.$refs['cropInput'+status].value = '';
                //         // console.log('图片上传成功:',self.urlImgBos + key)
                //         resolve(self.urlImgBos + key)
                //     })
                //     .catch(err => {
                //         // 上传失败，添加您的代码
                //         console.log(err);
                //         reject(err)
                //     });
                // self.client.on('progress', function (evt){
                //     // console.log(evt, ".....")
                //     // 监听上传进度
                //     if (evt.lengthComputable){
                //         self.imgPercentage = parseInt((evt.loaded / evt.total) * 100)+'';
                //         console.log(self.imgPercentage, "上传图片")
                //         self.imgPercentage = String(self.imgPercentage)
                //         // 满了，清空进度条
                //         if(self.imgPercentage == 100){
                //             self.imgPercentage = 0
                //         }
                //     }
                // });
            })
        },
        // 添加用户进入批次
        joinUserBatch (row) {
            this.selectedBatch = row;
            this.wxUserVisible = true;
            //  初始化
            this.wxUserData = [];
            this.wxUserPage = 1;
            this.wxUserTotal = 0;
            this.searchWxUserName = '';
        },
        // 获取微信授权用户
        async acquireAccreditWxUser () {
            const name = this.searchWxUserName;
            const page = this.wxUserPage;
            if (!name) {
                this.wxUserData = [];
                this.wxUserPage = 1;
                this.wxUserTotal = 0;
                // this.$message.error("请输入内容");
                return false;
            }
            const data = await obtainAccreditWxUser(name,page);
            this.wxUserData = data.data;
            this.wxUserTotal = data.total;
        },
        // 确定该用户加入 弹窗控制 显示
        confirmJoinUser (user) {
            this.selectedWxUser = user;
            this.confirmWxUserVisible = true;
        },
        // 搜索结果 页码
        async handleWxUserCurrentChange (val) {
            this.wxUserPage = val;
            await this.acquireAccreditWxUser();
        },
        // 提交该用户加入该批次
        async submitUserJoinCourseBatch () {
            console.log(this.selectedWxUser,'加入的用户');
            console.log(this.selectedBatch,'加入的批次');
            const checkApply = await checkStudentBatch(this.selectedBatch['batch_id'],this.selectedWxUser['user_info']['unionId']);
            console.log('校验是否报过该批次',checkApply)
            if (checkApply.status === 200) {
                const openId = this.selectedWxUser['user_info']['openId'];
                const unionId = this.selectedWxUser['user_info']['unionId'];
                const nickName = this.selectedWxUser['user_info']['nickName'];
                const typeName = this.selectedBatch['batch_type'] + '课程';
                const typeId = this.selectedBatch['type_id'];
                const batchId = this.selectedBatch['batch_id'];
                const payType = '4';
                console.log('校验是否报过该批次',openId,unionId,typeName);
                // 获取 微信支付 配置参数
                let wxPayParam = await obtainWXPayParam(openId, unionId, typeName, '0', 0,nickName, '', '', payType, typeId, batchId);
                console.log('wxPayParam',wxPayParam);
                if (wxPayParam.status === 201) {
                    // 创建订单成功
                    const out_trade_no = wxPayParam.data.out_trade_no;
                    // 确定订单
                    const order = this.confirmCourseIndent(out_trade_no);
                } else {
                   this.$message.error(wxPayParam.msg);  
                }
            } else {
                this.$message.error(checkApply.msg);
            }
        },
        // 确定 课程订单
        async confirmCourseIndent (orderId) {
            const self = this;
            const openId = self.selectedWxUser['user_info']['openId'];
            const unionId = self.selectedWxUser['user_info']['unionId'];
            const nickName = self.selectedWxUser['user_info']['nickName'];
            const typeName = self.selectedBatch['batch_type'] + '课程';
            const typeId = self.selectedBatch['type_id'];
            const batchId = self.selectedBatch['batch_id'];
            // 订单价格
            const actualPrice = self.selectedBatch['type_price'];
            const confirmFlag = await amendCourseIndent(orderId, actualPrice,0, nickName, '', '', openId, unionId,typeId, batchId)
            console.log(confirmFlag, '........')
            if (confirmFlag.status === 200) {
                // 保存用户信息
                const personalState = await preserveUserinfo(openId, batchId, confirmFlag.student_id, unionId)
                console.log(personalState, '.......保存用户信息')
                if (personalState.status === 200) {
                     this.$message({
                        message: "添加成功",
                        type: "success"
                    });
                    // 重新获取数据
                    self.wxUserVisible = false;
                    self.confirmWxUserVisible = false;
                    self.getData();
                    // if (self.$root.$mp.query.terrace_state === '2' && self.$root.$mp.query.operation_state === '1') {
                    //     console.log('.....创建订单成功121231321.......')
                    //     wx.redirectTo({ url: '../returnApp/main?amount='+(self.grossPrice * 100)})
                    //     return;
                    // }
                    // wx.setStorageSync('student_id', confirmFlag.student_id)
                    // wx.setStorageSync('batch_id', self.$root.$mp.query.batch_id)  
                    // showMessager('创建订单成功')
                    // console.log('创建订单成功', self.$root.$mp.query.batch_id)
                    // wx.switchTab({
                    //     url: '../dengesCourse/main'
                    // })
                }  
                // wx.switchTab({
                //   url: '../dengesCourse/main?batch_id='+self.$root.$mp.query.batch_id
                // })
            } else if(confirmFlag.status === 400) {
                showMessager('创建订单失败')
            } else {
                showMessager('创建订单失败,请联系客服')
            }
        },
        // 打开学员列表
        openStudentList (row) {
            this.$router.push({
                path: '/studentBatch',
                query: {
                    batch_id: row['batch_id']
                }
            })
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.del-dialog-cnt {
    font-size: 16px;
    text-align: center;
}
.crop-demo-btn{
    position: relative;
    width: 150px;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #409eff;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    box-sizing: border-box;
    text-align: center;
}
.crop-input{
    position: absolute;
    width: 150px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}
.pic-img {
    width: 60%;
    margin-top: 25px;
}
</style>
